package Java常用类的学习;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class ComputerComparator implements Comparator<Computer> {



    public int compare(Computer o1, Computer o2) {
//        brand 按照降序排列，所以要重写
        if(o1.brand.compareTo(o2.brand)>0)
            return -1;
        else if(o1.brand.compareTo(o2.brand)<0)
            return 1;
        else
            return o1.place.compareTo(o2.place);
    }

    public static void main(String[] args) {
        Set<Computer>set=new TreeSet<Computer>(new ComputerComparator());
        Computer computer1=new Computer("dell","shanghai");
        Computer computer2=new Computer("hp","shenzhen");
        Computer computer3=new Computer("hp","Guangzhou");
        Computer computer4=new Computer("lenovo","Beijing");
        Computer computer5=new Computer("dell","Beijing");
        set.add(computer1);
        set.add(computer2);
        set.add(computer3);
        set.add(computer4);
        set.add(computer5);
        Iterator<Computer> it=set.iterator();
        while(it.hasNext()){
            Computer c=it.next();
            System.out.println(c);
        }


    }
}
class Computer{
    String brand;
    String place;
    public Computer(String b,String p){
            this.brand=b;
            this.place=p;
    }
    public String toString(){
        return "computer brand:"+this.brand+","+"place:"+this.place;
    }
    public boolean equals(Object o){
        if(!(o instanceof Computer)) return false;
        Computer c1=(Computer)o;
        if(this.brand.equals(c1)&&this.place.equals(c1)) return true;
        return false ;
    }
    public int hashCode(){
        int code;
        return code=(brand==null?0:brand.hashCode());
    }
}
